<template>
	<view class="container">

		<view class="pos-f w-full navbar-area bg-main">
			<view class="state-area dflex-a">
				<view v-for="(item, index) in navList" :key="index" :class="{ active: tabCurrentIndex === index }"
					class="nav-item dflex-c pos-r fs padding-lr-lg h-full" @click="tabClick(index)">
					{{ item.title }}
				</view>
			</view>
		</view>

		<swiper :current="tabCurrentIndex" :disable-touch="true" class="swiper-box swiper-area h-full" duration="300"
			@change="changeTab">
			<swiper-item class="tab-content" v-for="(tabItem, tabIndex) in navList" :key="tabIndex">
				<scroll-view class="list-scroll-content h-full" scroll-y @scrolltolower="loadData">
					<view class="padding-lr" @click="use(item)" v-for="(item, index) in couponDatas" :key="index">
						<view class="coupon_box border-radius margin-top-sm bg-main"
							:class="[{ 'disabled': couponStatus != 0 }]">

							<view class="dflex-b">

								<view class="left pos-a h-full dflex-c dflex-flow-c">
									<view v-if="item.type == 1">
										<text class="price fs-big">{{ item.price }}</text>
									</view>
									<view v-if="item.type == 0">
										<text class="discount fs-big">{{ item.price * 10 }}</text>
									</view>
									<view class="fs-sm" v-if="item.price >= 1">直减{{ item.price }}元</view>
									<view class="fs-sm" v-else>全场通用</view>
								</view>

								<view class="right padding left_t flex1">
									<view class="dflex-b padding-bottom-xs">
										<view class="fwb fs">{{ item.title }}</view>
									</view>
									<view v-if="tabItem.state == 1 " class="ft-dark iconfont iconyishiyong"></view>
									<view v-if="tabItem.state == 2 " class="ft-dark iconfont iconyiguoqi"></view>
									<view class="dflex-b ft-dark fs-xs padding-bottom border-line">
										<view class="">有效期至 {{ item.end_time }}</view>
									</view>

								</view>

							</view>

						</view>
					</view>
				</scroll-view>
			</swiper-item>
		</swiper>
	</view>
</template>

<script>
	import {
		queryUserCouponsApi,

		//修改用户拥有的优惠券状态
		updateUserCouponsApi,
	} from '@/api/coupon.js'

	import {
		mapState
	} from 'vuex';

	export default {
		computed: {
			...mapState(["member"])
		},

		data() {
			return {
				tabCurrentIndex: 0,
				navData: {},


				couponDatas: [],
				// 要查询的优惠券状态
				couponStatus: 0,
				// 修改后优惠券状态
				new_status: 2,
				//当前时间戳
				new_time: '',
				// 防止重加载
				oneloading: true,

				navList: [{
						id: 0,
						title: '已领取',

					},

					{
						id: 1,
						title: '已使用',

					},
					{
						id: 2,
						title: '已过期',

					}
				],


				reqdata: {
					page: 1,
					rows: 10
				},
				scrollLeft: 0
			};
		},
		watch: {
			tabCurrentIndex(nv, ov) {
				this.loadData('tab_change', 1);
			}
		},
		onLoad(options) {
			this.loadData();
		},
		// 下拉刷新
		onPullDownRefresh() {
			// this.loadData('refresh');
		},
		// 上拉加载更多
		onReachBottom() {
			// this.loadData();
		},
		methods: {
			// 加载数据
			loadData(source = 'add', loading) {
				// 获取当前 nav
				let cur_nav = this.navList[this.tabCurrentIndex];
				this.couponStatus = cur_nav.id;
				this.reqdata.state = cur_nav.state;
				// this.couponStatus = 0;
				// this.getUserCouponsFunc();
				if (this.oneloading === true) {
					this.oneloading = false,
						this.getUserCouponsFunc();
				};
			},



			// swiper 切换
			changeTab(e) {
				this.tabCurrentIndex = e.target.current;
				// this.couponDatas = [];
				// this.getUserCouponsFunc();
				console.log("<==================changeTab")
			},
			// 顶部tab点击
			tabClick(index) {
				// this.couponDatas = [];
				this.tabCurrentIndex = index;
				this.couponStatus = index;
				console.log(this.couponStatus, "<=================index.this.couponStatus")
				this.getUserCouponsFunc();
				console.log("<==================tabClick")

			},
			// 去使用
			use(options) {

				// console.log(options,"<=================useruser1")
				// console.log(this.couponStatus,"<=================useruser2")
				if (this.couponStatus == 0) {
					this.$api.togoodslist({});
				} else {
					return;
				}
				// console.log(this.couponStatus,"<=================useruser3")



			},

			//查询用户优惠券
			async getUserCouponsFunc() {
				this.couponDatas = [];

				const response = await queryUserCouponsApi({
					uid: this?.member?.id ?? "",
					state: this?.couponStatus ?? 0,
				}).catch(() => {});
				if (response?.code === 200) {
					// 	const _data = [...this.orderList, ...(response?.data?.records ?? [])];
					this.couponDatas = [...this.couponDatas, ...(response?.data?.records ?? [])];
					// this.couponDatas =	this.couponDatas.map(item =>({
					// 	let item.state = item.users.users_coupons.state
					// }))

					// this.couponDatas = this.couponDatas.map(item => {
					//   // 创建一个新的对象，包含原来的属性和新添加的 state 字段
					//   return {
					//     ...item, // 将原来的属性拷贝到新对象中
					//     state: item?.users[0]?.users_coupons?.state // 添加新的 state 字段
					//   };
					// });

					console.log(this.couponDatas, "<=====couponDatas===========getUserCouponsFunc111");
					this.new_time = new Date().getTime();
					this.couponDatas = this.couponDatas.map(item => {
						// if(item.users_coupons.state === 0 ){
						let dateString = item.end_time;
						let dateObj = new Date(dateString).getTime();
						if (this.new_time > dateObj) {
							// 如果优惠券已过期，则改为过期状态
							if (item.users_coupons.state == 0) {
								this.new_status = 2;
								this.updateUserCouponsFunc(item);
							}
						}
						// 如果优惠券未过期，则改为未过期状态
						else if (this.new_time < dateObj) {
							if (item.users_coupons.state == 2) {
								this.new_status = 0;
								this.updateUserCouponsFunc(item);
							}
						}
						// }
						return item;
						// 创建一个新的对象，包含原来的属性和新添加的 state 字段
						// return {
						//   ...item, // 将原来的属性拷贝到新对象中
						//   state: item?.users[0]?.users_coupons?.state // 添加新的 state 字段
						// };
					});
					console.log(this.couponDatas, "<=====couponDatas===========getUserCouponsFunc222");

				} else {
					this.$api.msg(response?.msg ?? '服务器繁忙，请稍后再试');
				}
			},

			//修改优惠券状态
			async updateUserCouponsFunc(item) {
				const response = await updateUserCouponsApi({
					id: item?.users_coupons?.id ?? "",
					state: this?.new_status,
				}).catch(() => {})
				if (response.code == 200) {

				} else {
					this.$api.msg(response?.msg ?? "服务器繁忙，请稍后再试");
				}
			},
		}
	};
</script>

<style lang="scss">
	page,
	.container {
		min-height: 100%;
		background: $page-color-base;
	}

	.container {
		padding-top: 7vh;
	}

	/* 优惠券状态区 */
	.navbar-area {
		top: 0;
		white-space: nowrap;

		.state-area {
			height: 7vh;
			box-shadow: 0 1px 5px rgba(0, 0, 0, 0.06);
			z-index: 10;
		}

		.nav-item {
			flex: 1;

			&.active {
				&:after {
					content: '';
					position: absolute;
					left: 50%;
					transform: translate(-50%);
					bottom: 0;
					width: 44px;
					height: 0;
					border-bottom: 2px solid $base-color;
				}
			}
		}
	}

	/* #ifdef H5 */
	.navbar-area {
		margin-top: calc(44px + env(safe-area-inset-top));
	}

	/* #endif */

	/* 优惠券轮播区 */
	.swiper-area {
		height: 93vh;
	}

	.coupon_box {
		position: relative;

		&:last-child {
			margin-bottom: 20rpx;
		}

		.left {
			background-color: $base-color;
			color: #fff;
			width: 30%;

			.price {
				color: #fff !important;
			}
		}

		.right {
			margin-left: 30%;
		}

		.discount {
			font-weight: 580;
		}

		.discount::after {
			content: '折';
			font-size: 24rpx;
			margin-left: 6rpx;
		}

		.border-line {
			border-bottom: 1px dotted #ededed;
		}
	}

	.disabled {
		.left {
			background-color: #d9d9d9;
			color: #b2b2b2 !important;

			.price {
				color: #b2b2b2 !important;
			}
		}

		.iconfont {
			position: absolute;
			top: 0rpx;
			right: 30rpx;
			font-size: 110rpx;
		}
	}
</style>